<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="listQuery" class="demo-form-inline">
        <el-form-item label="素材名称">
          <el-input
            v-model.trim="listQuery.query"
            placeholder="请输入"
            style="width: 200px"
            clearable
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="listQuery.status"
            style="width: 90px"
            class="filter-item"
            placeholder="请选择"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="素材大类">
          <el-select
            v-model="listQuery.bigKindId"
            style="width: 90px"
            clearable
            class="filter-item"
            placeholder="请选择"
            @change="filterSmallKind($event)"
            @clear="showSelection = false"
          >
            <el-option
              v-for="item in kindList"
              :key="item.kindId"
              :label="item.name"
              :value="item.kindId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="素材小类">
          <el-select
            v-model="listQuery.smallKindId"
            style="width: 100px"
            clearable
            class="filter-item"
            placeholder="请选择"
          >
            <el-option
              v-for="item in smallKindList"
              :key="item.kindId"
              :label="item.name"
              :value="item.kindId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
          >搜索</el-button>
          <el-button
            class="filter-item"
            style="margin-left: 10px"
            type="primary"
            icon="el-icon-circle-plus"
            @click="handleCreate"
          >新增素材</el-button>
          <el-button
            v-if="showSelection"
            class="filter-item"
            style="margin-left: 10px"
            type="primary"
            icon="el-icon-copy-document"
            :loading="shopLoading"
            @click="copySource"
          >复制素材</el-button>
        </el-form-item>
      </el-form>
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button>
      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @selection-change="handleSelectionChange"
      @sort-change="sortChange"
    >
      <!-- <el-table-column label="素材图片" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        v-if="showSelection"
        :align="'center'"
        type="selection"
        width="50"
      />
      <el-table-column label="素材图片" min-width="120px" :align="'center'">
        <template slot-scope="{ row }">
          <el-image
            style="width: 100px; height: 60px"
            :src="
              row.photoUrl ||
                'https://wpimg.wallstcn.com/69a1c46c-eb1c-4b46-8bd4-e9e686ef5251.png'
            "
            :preview-src-list="[row.photoUrl]"
            fit="contain"
          />
        </template>
      </el-table-column>
      <el-table-column label="素材名称" min-width="120px" :align="'center'">
        <template slot-scope="{ row }">
          <span>{{ row.name || "-" }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="素材名称" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.name }}</span>
          <el-tag>{{ row.type | typeFilter }}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column
        label="素材价格(元)"
        :align="'center'"
        sortable
        :sort-method="feeSort"
      >
        <template slot-scope="{ row }">
          <span>{{ row.fee | doCountUnitFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="素材大类" :align="'center'">
        <template slot-scope="{ row }">
          <span>{{ row.bigKindIdName || "-" }}</span>
          <!-- <span>{{ row.bigKindId | bigKindIdFilter }}</span> -->
        </template>
      </el-table-column>
      <!-- <el-table-column label="素材小类" :align="'center'">
        <template slot-scope="{row}">
          <span>{{ row.smallKindId | smallKindIdFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column label="上架日期" width="150px" :align="'center'">
        <template slot-scope="{row}">
          <span>{{ row.updateTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column> -->
      <!-- 后边的参考使用 -->
      <!-- <el-table-column v-if="showReviewer" label="Reviewer" width="110px" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.reviewer }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Imp" width="80px">
        <template slot-scope="{row}">
          <svg-icon v-for="n in + row.importance" :key="n" icon-class="star" class="meta-item__icon" />
        </template>
      </el-table-column>
      <el-table-column label="Readings" align="center" width="95">
        <template slot-scope="{row}">
          <span v-if="row.pageviews" class="link-type" @click="handleFetchPv(row.pageviews)">{{ row.pageviews }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column> -->
      <el-table-column label="状态" class-name="status-col" width="85">
        <template slot-scope="{ row }">
          <el-tag :type="row.status | statusFilter">
            {{ row.status | statusNameFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        :align="'center'"
        width="180"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            修改
          </el-button>
          <!-- <el-button v-if="row.status!='published'" size="mini" type="success" @click="handleModifyStatus(row,'published')">
            发布
          </el-button>
          <el-button v-if="row.status!='draft'" size="mini" @click="handleModifyStatus(row,'draft')">
            下架
          </el-button> -->
          <el-button
            v-if="row.status != 'deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNumber"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
    <!-- 新增素材 -->
    <el-dialog
      :top="device != 'mobile' ? '4vh' : '0'"
      :width="device != 'mobile' ? '42%' : '380px'"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        :label-position="device != 'mobile' ? 'left' : 'left'"
        :label-width="device != 'mobile' ? '100px' : '80px'"
        :style="
          device != 'mobile'
            ? 'width: 300px; margin-left:100px;'
            : 'width: 300px; margin-left:50px;'
        "
      >
        <!--  -->
        <el-form-item label="素材名称" class="filter-item" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="素材图片" class="filter-item" prop="photoUrl">
          <el-upload
            v-loading="upImgloading"
            class="avatar-uploader"
            :action="actionUrl"
            :show-file-list="false"
            name="multipartFile"
            :data="firePostData"
            :on-error="handleUpladLoadingError"
            :on-progress="handleUpladLoading"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="type">
          <el-select v-model="temp.type" class="filter-item" placeholder="请选择">
            <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="素材价格(元)" prop="fee" class="filter-item">
          <el-input v-model="temp.numberFee" type="number" min="0" />
        </el-form-item>
        <el-form-item label="素材大类" prop="bigKindId">
          <el-select
            v-model="temp.bigKindId"
            class="filter-item"
            placeholder="请选择"
          >
            <el-option
              v-for="item in kindList"
              :key="item.kindId"
              :label="item.name"
              :value="item.kindId"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="素材小类" prop="smallKindId">
          <el-select v-model="temp.smallKindId" class="filter-item" placeholder="请选择">
            <el-option v-for="item in smallKindListDialog" :key="item.kindId" :label="item.name" :value="item.kindId" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="temp.status"
            class="filter-item"
            placeholder="请选择"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="规格" prop="specs">
          <el-cascader
            ref="cascade"
            v-model="specsIds"
            :options="specsOptions"
            :props="{ multiple: true }"
            collapse-tags
            @change="cascaderChange($event)"
          />
          <!-- clearable -->
        </el-form-item>
        <!-- <el-form-item label="Imp">
          <el-rate v-model="temp.importance" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" :max="3" style="margin-top:8px;" />
        </el-form-item> -->
        <!-- <el-form-item label="备注">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          提交
        </el-button>
      </div>
    </el-dialog>

    <!-- 批量添加素材 -->
    <el-dialog
      :top="device != 'mobile' ? '4vh' : '0'"
      :width="device != 'mobile' ? '42%' : '380px'"
      :title="'批量复制'"
      :visible.sync="dialogCopyVisible"
    >
      <el-form :inline="true" :model="shopQuery" class="demo-form-inline">
        <el-form-item label="商家名称">
          <el-input
            v-model="shopQuery.query"
            placeholder="请输入名称"
            style="width: 200px"
            clearable
            class="filter-item"
            @keyup.enter.native="handleShopFilter"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleShopFilter"
          >搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :key="1"
        :data="shopList"
        border
        fit
        highlight-current-row
        style="width: 100%"
        @current-change="handleCurrentChange"
      >
        <!-- <el-table-column :align="'center'" type="selection" width="50" /> -->
        <el-table-column label="商家名称" min-width="120px" :align="'center'">
          <template slot-scope="{ row }">
            <span>{{ row.name || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" class-name="status-col" width="85">
          <template slot-scope="{ row }">
            <el-tag :type="row.status | statusFilter">
              {{ row.status | shopStatusNameFilter }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="商家电话" :align="'center'">
          <template slot-scope="{ row }">
            <span>{{ row.serialNumber || "-" }}</span>
            <!-- <span>{{ row.bigKindId | bigKindIdFilter }}</span> -->
          </template>
        </el-table-column>
        <el-table-column label="商家位置" :align="'center'">
          <template slot-scope="{ row }">
            <span>{{ row.address }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="copySourcePost()"> 绑定 </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table
        :data="pvData"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="dialogPvVisible = false"
        >确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as imageConversion from 'image-conversion'
// import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
import { getAccountListList } from '@/api/shop'
import {
  getSourceMaterialList,
  sourceUpdate,
  sourceInsert,
  sourceDelete,
  batchInsertCommodity,
  getQuerySpecsList
} from '@/api/source'
import { MessageBox } from 'element-ui'
import waves from '@/directive/waves' // waves directive
import { parseTime, doCountUnit } from '@/utils'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]
// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})
let bigKindIdListArr = []
export default {
  name: 'SourchList',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'success',
        1: 'danger'
      }
      return statusMap[status * 1]
    },
    shopStatusNameFilter(status) {
      const statusMap = [
        { key: 0, value: '营业中' },
        { key: 1, value: '闭店中' }
      ]
      const index = statusMap.findIndex((i) => {
        return i && i.key === status * 1
      })
      return statusMap[index].value
    },
    statusNameFilter(status) {
      const statusMap = [
        { key: 0, value: '上架中' },
        { key: 1, value: '下架中' }
      ]
      const index = statusMap.findIndex((i) => {
        return i && i.key === status * 1
      })
      return statusMap[index].value
    },
    doCountUnitFilter(number) {
      return doCountUnit(number)
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    },
    bigKindIdFilter(id) {
      if (bigKindIdListArr.length === 0) {
        return '-'
      }
      const number = bigKindIdListArr.findIndex((i) => {
        return i && i.kindId === id
      })
      if (number > -1) {
        return bigKindIdListArr[number].name
      }
      return '-'
    }
  },
  data() {
    const validatePhoto = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请上传图片'))
      } else {
        callback()
      }
    }
    return {
      imageUrl: '',
      tableKey: 0,
      list: null,
      total: 0,
      specsIds: null,
      listLoading: true,
      actionUrl: `${process.env.VUE_APP_BASE_API}/image/upload`,
      showSelection: false,
      upImgloading: false,
      firePostData: {
        token: getToken()
      },
      shopQuery: {
        query: ''
      },
      dialogCopyVisible: false,
      shopLoading: false,
      shopList: [],
      listQuery: {
        pageNumber: 1,
        pageSize: 20,
        bigKindId: '',
        smallKindId: '',
        query: '',
        status: '0'
      },
      smallKindList: [],
      specsOptions: [],
      kindList: [],
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],
      statusOptions: [
        {
          key: '0',
          value: '上架'
        },
        {
          key: '1',
          value: '下架'
        }
      ],
      showReviewer: false,
      endSpecs: [],
      temp: {
        photoUrl: '',
        name: '',
        remark: '',
        fee: 0,
        numberFee: 0,
        inventory: 0,
        bigKindId: '',
        smallKindId: '',
        specs: '',
        status: '0'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        fee: [{ required: true, message: '必填项', trigger: 'blur' }],
        bigKindId: [{ required: true, message: '必填项', trigger: 'change' }],
        // smallKindId: [{ required: true, message: '必填项', trigger: 'change' }],
        status: [{ required: true, message: '必填项', trigger: 'change' }],
        name: [{ required: true, message: '必填项', trigger: 'blur' }],
        photoUrl: [
          { required: true, message: '必填项', validator: validatePhoto }
        ]
      },
      downloadLoading: false
    }
  },
  computed: {
    ...mapGetters(['device']),
    smallKindListDialog() {
      if (this.kindList.length === 0) {
        return []
      }
      const list = this.kindList.find((i) => {
        return i && i.kindId === this.temp.bigKindId
      })
      if (list) {
        return list.kind
      } else {
        return []
      }
    }
  },
  created() {
    this.getList()
    this.getQuerySpecsList()
  },
  methods: {
    feeSort(a, b) {
      return a.fee - b.fee
    },
    handleUpladLoadingError() {
      this.upImgloading = false
    },
    handleUpladLoading() {
      this.upImgloading = true
    },
    handleAvatarSuccess(res, file) {
      this.upImgloading = false
      if (res.respCode === '000') {
        this.temp.photoUrl = res.result
        this.imageUrl = URL.createObjectURL(file.raw)
      } else {
        this.$message.error('上传失败')
      }
    },
    beforeAvatarUpload(file) {
      return new Promise((resolve, reject) => {
        const isLt2M = file.size / 1024 / 1024 < 20 // 判定图片大小是否小于20MB
        // 压缩到400KB,这里的400就是要压缩的大小,可自定义
        if (isLt2M) {
          imageConversion.compressAccurately(file, 400).then((res) => {
            resolve(res)
          })
        } else {
          reject()
        }
      })
    },
    filterSmallKind() {
      if (this.kindList.length === 0) {
        this.smallKindList = []
        return []
      }
      const list = this.kindList.find((i) => {
        return i && i.kindId === this.listQuery.bigKindId
      })
      if (list) {
        this.smallKindList = list.kind
        return list.kind
      } else {
        this.smallKindList = []
        return []
      }
    },
    handleSelectionChange(val) {
      this.choseSourceList = val
    },
    handleCurrentChange(val) {
      this.currentRow = val
    },
    handleShopFilter() {
      const params = {
        pageNumber: 1,
        pageSize: 100000,
        query: this.shopQuery.query
      }
      getAccountListList(params)
        .then((res) => {
          this.shopLoading = false
          const data = res
          this.shopList = data
        })
        .catch(() => {
          this.shopLoading = false
        })
    },
    copySourcePost() {
      const currentRow = this.currentRow
      const source = this.choseSourceList
      if (!currentRow) {
        this.$message.error('请选择要绑定的商家!')
      }
      const sourceId = []
      source.map((i) => {
        sourceId.push(i.commodityId)
        return i
      })
      this.$confirm(
        `确定要把选中的${sourceId.length}件素材绑定给${currentRow.name}嘛?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          const params = {
            commodityIds: sourceId.join(','),
            mId: currentRow.id
          }
          batchInsertCommodity(params)
            .then(() => {
              loading.close()
              this.dialogCopyVisible = false
              this.$message({
                type: 'success',
                message: '绑定成功!'
              })
            })
            .catch(() => {
              loading.close()
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    copySource() {
      if (this.choseSourceList.length === 0) {
        this.$message.error('请选择要添加的素材')
        return
      }
      this.shopLoading = true
      const params = {
        pageNumber: 1,
        pageSize: 100000,
        query: ''
      }
      getAccountListList(params)
        .then((res) => {
          this.shopLoading = false
          const data = res
          this.shopList = data
          this.dialogCopyVisible = true
        })
        .catch(() => {
          this.shopLoading = false
        })
    },
    cascaderChange(e) {
      const list = e
      if (list.length === 0) {
        this.temp.specs = null
        return
      }
      const firstArr = this.endSpecs
      list.map((i) => {
        const index = firstArr.findIndex((j) => {
          return j && j.specsId == i[0]
        })
        if (index > -1) {
          const specsList = firstArr[index].specsList
          if (specsList && specsList.length > 0) {
            const oindex = specsList.findIndex((k) => k.specsId == i[1])
            if (oindex < 0) {
              specsList.push({
                specsId: i[1]
              })
            }
            this.endSpecs[index].specsList = specsList
          } else {
            this.endSpecs[index].specsList = [
              {
                specsId: i[1]
              }
            ]
          }
        } else {
          // 之前没有
          this.endSpecs.push({
            specsId: i[0],
            specsList: [
              {
                specsId: i[1]
              }
            ]
          })
        }
        return i
      })
      this.temp.specs = JSON.stringify(this.endSpecs)
    },
    getQuerySpecsList() {
      getQuerySpecsList()
        .then((res) => {
          const data = res
          data.map((i) => {
            i.value = i.specsId
            i.label = i.specsName
            i.children = i.list.map((j) => {
              j.value = j.specsId
              j.label = j.specsName
              return j
            })
            return i
          })
          this.specsOptions = data
        })
        .catch(() => {})
    },
    getList() {
      this.listLoading = true
      getSourceMaterialList(this.listQuery)
        .then((response) => {
          this.list = response.sourceMaterialList
          this.kindList = response.kindList
          bigKindIdListArr = response.kindList
          this.list.map((i) => {
            bigKindIdListArr.map((j) => {
              if (i.bigKindId === j.kindId) {
                i.bigKindIdName = j.name
              }
              return j
            })
            return i
          })
          if (this.list.length > 0 && this.listQuery.bigKindId !== '') {
            this.showSelection = true
          } else {
            this.showSelection = false
          }
          this.total = response.total
          setTimeout(() => {
            this.listLoading = false
          }, 1000)
        })
        .catch(() => {
          setTimeout(() => {
            this.listLoading = false
          }, 1000)
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.imageUrl = null
      this.temp = {
        name: '',
        remark: '',
        fee: 0,
        numberFee: 0,
        photoUrl: '',
        inventory: 0,
        bigKindId: '',
        specs: null,
        smallKindId: '',
        status: '0'
      }
      this.specsIds = null
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.upImgloading = false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      // this.$prompt('请输入操作码', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   center: true,
      //   inputErrorMessage: '操作码不正确'
      // }).then(({ value }) => {
      //   const arr = ['4567', '8921', '3739', '3245', '2930', '8889', '2341']
      //   const ovalue = value + ''
      //   const index = arr.findIndex((i) => {
      //     return i === ovalue
      //   })
      //   if (index < 0) {
      //     this.$message.error('您没权限操作')
      //     return
      //   }
      // }).catch(() => {

      // })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.fee = this.temp.numberFee*100
          sourceInsert(this.temp).then(() => {
            // this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '新增成功',
              type: 'success',
              duration: 1500
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.$prompt('请输入操作码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        inputErrorMessage: '操作码不正确'
      })
        .then(({ value }) => {
          const arr = ['4567', '8921', '3739', '3245', '2930', '8889', '2341']
          const ovalue = value + ''
          const index = arr.findIndex((i) => {
            return i === ovalue
          })
          if (index < 0) {
            this.$message.error('您没权限操作')
            return
          }
          const data = row
          const specsList = data.specsList
          const mArr1 = []
          if (specsList && specsList.length > 0) {
            const mArr = []
            specsList.map((i) => {
              const mSpecsList = []
              i.list.map((j) => {
                mArr.push([i.specsId, j.specsId])
                mSpecsList.push({
                  specsId: j.specsId
                })
                return j
              })
              mArr1.push({
                specsId: i.specsId,
                specsList: mSpecsList
              })
            })
            this.specsIds = mArr
          }
          // this.specsOptions.map()
          data.fee && (data.numberFee = (data.fee / 100).toFixed(2))
          this.temp = Object.assign({}, data) // copy obj
          if (mArr1.length > 0) {
            this.temp.specs = JSON.stringify(mArr1)
          }
          this.imageUrl = data.photoUrl || ''
          this.temp.timestamp =
            (this.temp.timestamp && new Date(this.temp.timestamp)) || ''
          this.dialogStatus = 'update'
          this.upImgloading = false
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        })
        .catch(() => {})
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.fee = this.temp.numberFee*100
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          sourceUpdate(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 1500
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$prompt('请输入操作码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        inputErrorMessage: '操作码不正确'
      })
        .then(({ value }) => {
          const arr = ['4567', '8921', '3739', '3245', '2930', '8889', '2341']
          const ovalue = value + ''
          const index = arr.findIndex((i) => {
            return i === ovalue
          })
          if (index < 0) {
            this.$message.error('您没权限操作')
            return
          }
          // 下边是最开始的代码
          MessageBox.confirm('确定要删除此素材么？', '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            sourceDelete({
              commodityId: row.commodityId
            }).then(() => {
              this.$notify({
                message: '删除成功',
                type: 'success',
                duration: 1500
              })
              this.getList()
            })
          })
        })
        .catch(() => {})
    },
    handleFetchPv(pv) {
      // fetchPv(pv).then(response => {
      //   this.pvData = response.data.pvData
      //   this.dialogPvVisible = true
      // })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then((excel) => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = [
          'timestamp',
          'title',
          'type',
          'importance',
          'status'
        ]
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style lang="scss" scoped>
.el-dialog__body {
  .el-input {
    width: 201px;
  }

  .avatar-uploader {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;

    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;

      &:hover {
        border-color: #409eff;
      }
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
  }
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
